import React, { useState, useEffect } from 'react';
import { Layout, List, Typography, Divider, Empty, Spin, message, Rate, Input, Button, Pagination } from 'antd';
import { useParams, useLocation } from 'react-router-dom';
import ReviewCard from '../components/ReviewCard';
import { fetchReviews } from '../services/api';

const { Content } = Layout;
const { Title, Text } = Typography;

/**
 * 评价列表页面
 * 
 * 功能：
 * - 展示用户或商品的评价列表
 * - 支持评分筛选
 * - 支持分页
 * - 显示平均评分和统计信息
 */
const ReviewList = () => {
  const [reviews, setReviews] = useState([]);
  const [loading, setLoading] = useState(true);
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 10,
    total: 0
  });
  const [ratingFilter, setRatingFilter] = useState(0);
  const [stats, setStats] = useState({
    average: 0,
    count: 0,
    distribution: [0, 0, 0, 0, 0]
  });

  const params = useParams();
  const location = useLocation();

  // 加载评价数据
  const loadReviews = async (page = 1, filterRating = ratingFilter) => {
    setLoading(true);
    try {
      const requestParams = {
        page,
        page_size: pagination.pageSize,
        rating: filterRating > 0 ? filterRating : undefined
      };

      // 根据路由参数确定是用户评价还是商品评价
      let response;
      if (params.userId) {
        response = await fetchReviews(`users/${params.userId}`, requestParams);
      } else if (params.productId) {
        response = await fetchReviews(`products/${params.productId}`, requestParams);
      }

      if (response) {
        setReviews(response.items);
        setPagination(prev => ({
          ...prev,
          current: page,
          total: response.total
        }));
        
        // 更新统计信息
        setStats({
          average: response.average_rating || 0,
          count: response.total,
          distribution: response.rating_distribution || [0, 0, 0, 0, 0]
        });
      }
    } catch (error) {
      message.error('加载评价失败');
    } finally {
      setLoading(false);
    }
  };

  // 处理分页变化
  const handlePageChange = (page) => {
    loadReviews(page);
  };

  // 处理评分筛选
  const handleRatingFilter = (value) => {
    setRatingFilter(value);
    setPagination(prev => ({ ...prev, current: 1 }));
    loadReviews(1, value);
  };

  // 计算评分分布百分比
  const getDistributionPercentage = (count) => {
    if (stats.count === 0) return 0;
    return Math.round((count / stats.count) * 100);
  };

  // 初始化加载
  useEffect(() => {
    loadReviews(1);
  }, [params.userId, params.productId]);

  return (
    <Layout className="review-list-layout">
      <Content className="review-list-content">
        {/* 页面标题和统计 */}
        <div className="review-list-header">
          <Title level={3} className="page-title">
            {params.userId ? '用户评价' : params.productId ? '商品评价' : '评价列表'}
          </Title>
          
          {/* 评分统计 */}
          <div className="rating-stats">
            <div className="overall-rating">
              <Text strong className="average-score">{stats.average.toFixed(1)}</Text>
              <Rate disabled value={stats.average} allowHalf className="main-rating" />
              <Text type="secondary" className="review-count">{stats.count} 条评价</Text>
            </div>
            
            {/* 评分分布 */}
            <div className="rating-distribution">
              {[5, 4, 3, 2, 1].map((star) => {
                const count = stats.distribution[5 - star];
                const percentage = getDistributionPercentage(count);
                
                return (
                  <div key={star} className="distribution-item">
                    <div className="star-label">
                      <Text>{star}星</Text>
                      <Text type="secondary">({count})</Text>
                    </div>
                    <div className="progress-bar">
                      <div 
                        className="progress-fill" 
                        style={{ width: `${percentage}%` }}
                      />
                    </div>
                    <Text type="secondary">{percentage}%</Text>
                  </div>
                );
              })}
            </div>
          </div>
        </div>

        <Divider />

        {/* 筛选和搜索 */}
        <div className="review-filters">
          <div className="rating-filters">
            <Text>筛选评分：</Text>
            <Rate
              value={ratingFilter}
              onChange={handleRatingFilter}
              allowHalf
              className="filter-rating"
              tooltips={['全部', '1星', '2星', '3星', '4星', '5星']}
            />
          </div>
        </div>

        {/* 评价列表 */}
        <div className="reviews-container">
          {loading ? (
            <Spin size="large" className="loading" />
          ) : reviews.length > 0 ? (
            <>
              <List
                dataSource={reviews}
                renderItem={(review) => (
                  <List.Item>
                    <ReviewCard review={review} showActions={false} />
                  </List.Item>
                )}
                split={false}
                locale={{ emptyText: <Empty description="暂无评价" /> }}
              />
              
              {/* 分页控件 */}
              <div className="pagination-container">
                <Pagination
                  current={pagination.current}
                  pageSize={pagination.pageSize}
                  total={pagination.total}
                  onChange={handlePageChange}
                  showTotal={(total) => `共 ${total} 条评价`}
                />
              </div>
            </>
          ) : (
            <Empty description="暂无评价" className="empty-reviews" />
          )}
        </div>
      </Content>
    </Layout>
  );
};

export default ReviewList;
